﻿#ifndef ANDYRP_LIGHTING_INCLUDED
#define ANDYRP_lIGHTING_INCLUDED

float3 GetDiffuse(Surface surface, float3 dir)
{
	return saturate(dot(surface.normal, dir));
}

float GetDistance(float3 lV)
{
	return max(dot(lV, lV), 0.0001);
}

float GetRangeFade(float3 lV, float lA)
{
	float rangeFade = dot(lV, lV) * lA;
	rangeFade = saturate(1.0 - rangeFade * rangeFade);
	rangeFade *= rangeFade;

	return rangeFade;
}

float GetSpotFade(float3 lD, Light light)
{
	float spotFade = dot(light.spotLightDir,lD);
	spotFade = saturate(spotFade * light.atten.z + light.atten.w);
	spotFade *= spotFade;

	return spotFade;

}


float3 GetIncomingLight(Surface surface,Light light,float shadowAtten)
{
	float3 lightVector = light.directionOrpos.xyz - surface.worldPos * light.directionOrpos.w;
	float3 lightDir = normalize(lightVector);
	
	float rangeFade = GetRangeFade(lightVector, light.atten.x);
	float distance = GetDistance(lightVector);
	float spotFade = GetSpotFade(lightDir, light);
	float3 diffuse = GetDiffuse(surface, lightVector);
	diffuse *= shadowAtten * spotFade * rangeFade / distance;
	float3 color = diffuse * light.color;
	return color;
}

float3 GetLighting(Surface surface)
{	

	float3 light = 0.0;
	real4  lightInd0 = unity_LightIndices[0];

	for(int i = 0; i < unity_LightData.y; i++)
	{
		int lightIndex = lightInd0[i];
        Light _light = GetLight(lightIndex);
        float sa = ShadowAttenuation(surface.worldPos);
		light += GetIncomingLight(surface, _light,sa);
	}
	return light;	
}

#endif